<template>
  <editor :key="editorKey" v-model="content" :init="init" :id="props.id" />
</template>

<script setup>
import tinymce from "tinymce/tinymce"; // 必须保留, 否则报错
import Editor from "@tinymce/tinymce-vue";
import "tinymce/icons/default/icons";
import "tinymce/models/dom"; // 一定要引入
import "tinymce/themes/silver"; // 界面UI主题
import "tinymce/plugins/image";
import "tinymce/plugins/table";
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/wordcount"; // 文字计数
import "tinymce/plugins/preview"; // 预览
import "tinymce/plugins/emoticons"; // emoji表情
import "tinymce/plugins/emoticons/js/emojis.js"; //必须引入这个文件才有表情图库
import "tinymce/plugins/code"; // 编辑源码
import "tinymce/plugins/link"; // 链接插件
import "tinymce/plugins/advlist"; //高级列表
import "tinymce/plugins/codesample"; //代码示例
import "tinymce/plugins/autoresize"; // 自动调整编辑器大小
import "tinymce/plugins/quickbars"; // 光标处快捷提示
import "tinymce/plugins/nonbreaking"; //插入不间断空格
import "tinymce/plugins/searchreplace"; //查找替换
import "tinymce/plugins/autolink"; //自动链接
import "tinymce/plugins/directionality"; //文字方向
import "tinymce/plugins/visualblocks"; //显示元素范围
import "tinymce/plugins/visualchars"; //显示不可见字符
import "tinymce/plugins/charmap"; // 特殊符号
import "tinymce/plugins/nonbreaking"; //插入不间断空格
import "tinymce/plugins/insertdatetime"; //插入日期时间
import "tinymce/plugins/importcss"; //引入自定义样式的css文件
import "tinymce/plugins/accordion"; // 可折叠数据手风琴模式
import "tinymce/plugins/anchor"; //锚点
import "tinymce/plugins/fullscreen";
import useSettingsStore from "@/store/modules/settings";

const props = defineProps({
  modelValue: { type: String },
  height: { type: Number, default: 400 },
  id: { type: String, default: () => "tinymce" + new Date().getTime().toString() },
  plugins: {
    type: [String, Array],
    default:
      "preview searchreplace autolink image directionality visualblocks visualchars fullscreen link code codesample table charmap nonbreaking insertdatetime advlist lists wordcount"
  },
  toolbar: {
    type: [String, Array],
    default:
      "code undo redo restoredraft | paste pastetext | forecolor backcolor bold italic underline strikethrough link image codesample | fullscreen preview | alignleft aligncenter alignright alignjustify outdent indent formatpainter | \
    styles codeformat fontfamily fontsize | bullist numlist | blockquote subscript superscript removeformat | table tablecellborderstyle \
    charmap pagebreak insertdatetime | resource"
  }
});

const emit = defineEmits(["update:modelValue", "change"]);

let content = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  }
});
const settingsStore = useSettingsStore();
const mode = computed(() => settingsStore.mode);
const list = ref([]);
const resource = ref();
const resourceVisible = ref(false);

//定义一个对象 init初始化
const init = reactive({
  menubar: false, // 菜单栏显隐
  language_url: "/tinymce/i18n/zh_CN.js", // 语言包的路径，具体路径看自己的项目
  language: "zh_CN",
  skin_url: mode.value === "light" ? "/tinymce/skins/ui/tinymce-5" : "/tinymce/skins/ui/tinymce-5-dark",
  editable_root: props.editable_root,
  height: props.height,
  toolbar_mode: "wrap",
  plugins: props.plugins,
  toolbar: props.toolbar,
  branding: false, // 是否禁用“Powered by TinyMCE”
  promotion: false, //去掉 upgrade
  paste_data_images: true, //允许粘贴图像
  image_dimensions: false, //去除宽高属性
  convert_urls: false,
  link_default_target: "_blank",
  link_context_toolbar: true,
  // 默认快捷菜单
  quickbars_insert_toolbar: "image codesample table",
  // 选中图片的快捷提示
  quickbars_image_toolbar: "alignleft aligncenter alignright | rotateleft rotateright | imageoptions",
  editimage_toolbar: "rotateleft rotateright | flipv fliph | editimage imageoptions",
  // 文字样式
  font_family_formats: "Arial=arial,helvetica,sans-serif; 宋体=SimSun; 微软雅黑=Microsoft Yahei; Impact=impact,chicago;", //字体
  font_size_formats: "11px 12px 14px 16px 18px 24px 36px 48px 64px 72px", //文字大小
  image_caption: true,
  editimage_cors_hosts: ["picsum.photos"],
  noneditable_class: "mceNonEditable",
  content_style: "body { font-family:Helvetica,Arial,sans-serif; font-size:16px }p {margin:3px; line-height:24px;}",
  image_advtab: true,
  importcss_append: true,
  paste_webkit_styles: "all",
  paste_merge_formats: true,
  nonbreaking_force_tab: false,
  paste_auto_cleanup_on_paste: false,
  file_picker_types: "file",
  quickbars_selection_toolbar: "bold italic | quicklink h2 h3 blockquote quickimage quicktable",
  autoresize_bottom_margin: 20,
  min_height: props.minHeight,
  content_css: "/tinymce/skins/content/default/content.css", //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
  //图片上传  -实列 具体请根据官网补充-
  images_upload_handler: function (blobInfo, progress) {
    new Promise((resolve, reject) => {
      let file = blobInfo.blob();
      if (file.size / 1024 / 1024 > 200) {
        reject({
          message: "上传失败，图片大小请控制在 200M 以内",
          remove: true
        });
      }
      const formData = new FormData();
      formData.append("file", file);
      axios
        .post("/api/upload/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data"
          },
          onUploadProgress: progressEvent => {
            progress(Math.round((progressEvent.loaded / progressEvent.total) * 100));
          }
        })
        .then(res => {
          resolve(res.data.url);
        })
        .catch();
    });
  }
});

const editorKey = ref(new Date().getTime());
watch(
  () => list.value,
  imgs => {
    let tmp = "";
    imgs.map(img => {
      if (
        img.indexOf(".jpg") > -1 ||
        img.indexOf(".png") > -1 ||
        img.indexOf(".bmp") > -1 ||
        img.indexOf(".jpeg") > -1 ||
        img.indexOf(".svg") > -1 ||
        img.indexOf(".gif") > -1
      ) {
        tmp += `<img src=${img} width="100%"  alt=""/>`;
      }
    });
    content.value = content.value ? content.value + tmp : tmp;
    resource.value?.clearSelecteds();
    resourceVisible.value = false;
  }
);
watch(
  () => content.value,
  vl => emit("change", vl)
);
</script>
